

#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>

#include "tcpa_monitor.h"

struct option long_options[] = {
/*      参数全称,           是否跟参数, NULL, 参数简称 */
    { "tcpa_cfg_path",      1,       NULL,  'c'},
    { "whitelist_path",     1,       NULL,  'w'},
    { "rcstnetcfg_path",    1,       NULL,  'r'},
    { "help",               0,       NULL,  'h'},
    { 0,                    0,        0,     0},
};

int decode_input_parameter(int argc, char* argv[], tcpa_monitor_t *tcpam)
{
    int ch;
    while((ch = getopt_long(argc, argv, "c:w:r:", long_options, NULL)) != -1) {
        switch(ch) {
            case 'c': {
                tcpa_cfg_file_t *tcpa_cfg_file = &tcpam->tcpam_cfg_file_ctx.tcpa_cfg_file[TCPA_CFG];
                strcpy(tcpa_cfg_file->cfg_name, "tcpa_cfg");
                // 确保不会溢出，并且末尾有空字符
                int len = strlen(optarg);
                if (len >= sizeof(tcpa_cfg_file->file_path)) {
                    TCPAM_LOG_ERROR("tcpa_cfg_path is too long.");
                    return -1;
                }
                strcpy(tcpa_cfg_file->file_path, optarg);
                tcpa_cfg_file->file_path[len] = '\0'; // 确保末尾有空字符
            }
            break;
            case 'w': {
                tcpa_cfg_file_t *whitelist_cfg_file = &tcpam->tcpam_cfg_file_ctx.tcpa_cfg_file[WHITELIST_CFG];
                strcpy(whitelist_cfg_file->cfg_name, "whitelist_cfg");

                // 确保不会溢出，并且末尾有空字符
                int len = strlen(optarg);
                if (len >= sizeof(whitelist_cfg_file->file_path)) {
                    TCPAM_LOG_ERROR("tcpa_whitelist_path is too long.");
                    return -1;
                }
                strcpy(whitelist_cfg_file->file_path, optarg);
                whitelist_cfg_file->file_path[len] = '\0'; // 确保末尾有空字符
            }
            break;
            case 'r': {
                // 确保不会溢出，并且末尾有空字符
                int len = strlen(optarg);
                if (len >= sizeof(tcpam->pep_svn_info.file_path)) {
                    TCPAM_LOG_ERROR("rcstnetcfg_path is too long.");
                    return -1;
                }
                strcpy(tcpam->pep_svn_info.file_path, optarg);
                tcpam->pep_svn_info.file_path[len] = '\0'; // 确保末尾有空字符
            }
            break;
            case 'h': {
                printf("Usage: %s -c tcpa_cfg_path -w whitelist_path -R rcstnetcfg_path\n", argv[0]);
                printf("tcpa_cfg_path defalut[%s] whitelist_path defalut[%s] rcstnetcfg_path defalut[%s]\n", TCPA_CFG_FILE_DEFAULT_PATH, TCPA_WHITELIST_CFG_FILE_DEFAULT_PATH, TD_RCSTNETCFG_FILE_PATH);
                exit(0);
            }
            default: {
                TCPAM_LOG_ERROR("unknown parameter[%s].", optarg);
                return -1;
            }
            break;
        }
    }
    return 0;
}
